package com.bite.common.message.utils;

import com.alibaba.fastjson2.JSON;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class SendUtils {
    /**
     * 发送POST请求
     * @param url 请求API的URL
     * @param data POST数据，Map类型
     * @return API返回的JSON数据
     * @throws Exception
     */
    public static String sendPostRequest(String url, Map<String, Object> data) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");

        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());

        String postData = convertMapToJsonString(data);
        wr.writeBytes(postData);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }

    /**
     * 把Map类型数据转换成JSON字符串
     * @param map Map类型数据
     * @return 转换后的JSON字符串
     * @throws Exception
     */
    private static String convertMapToJsonString(Map<String, Object> map) throws Exception {
        return JSON.toJSONString(map);
    }
}
